package com.launcher.wkang.fragment;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.RemoteException;
import android.provider.Settings;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.annotation.RequiresApi;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.Fragment;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;


import com.baidu.location.BDAbstractLocationListener;
import com.baidu.location.BDLocation;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.google.gson.Gson;
import com.launcher.wkang.App;
import com.launcher.wkang.R;
import com.launcher.wkang.activity.IntermediaryActivity;
import com.launcher.wkang.activity.LauncherActivity;
import com.launcher.wkang.activity.LauncherActivity1;
import com.launcher.wkang.bean.AppInfo;
import com.launcher.wkang.bean.WeatherBean;
import com.launcher.wkang.util.NetUtils;
import com.launcher.wkang.util.PhoneUtil;
import com.launcher.wkang.util.Url;
import com.launcher.wkang.view.Watch;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

import static cn.jpush.android.api.JPushInterface.getRegistrationID;

public class Fragment1 extends Fragment implements View.OnClickListener {
    private Watch watchView;
    private View view;
    private TextView textView1;
    private TextView textView2;
    private TextView textView3;
    private TextView timeDateWeek;
    private TextView cityText;
    private TextView cityWhrear;
    private TextView whrearInfo;
    public LocationClient mLocationClient = null;
    private ImageView weatherIcon;
    private TextView  currentTemperature;
    private MyLocationListener myListener = new MyLocationListener();
    private static final int BAIDU_READ_PHONE_STATE =100;
    private static final int SECURE_SETTINGS=101;
    private static final int TIME_REQUEST =1001;
    private static final int LOCATION_REQUEST =1002;
    private static final int WHREAR_REQUEST =1003;
    private static final int READ_PHONE_STATE=102;
//    此变量修改 为全局变量
//    private WeatherBean weatherBean;
    private String city;
    private double latitude ;    //获取纬
    // 度信息
    private double longitude ;
    private int getWetherFrequency;
    public LinearLayout hotLayout;
    public TextView hintText;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Log.d("Fragment","Fragment1 onCreate");
        getWetherFrequency=1;
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
         view =getActivity().getLayoutInflater().inflate(R.layout.fragment_layout1,null);
         initView();
         initData();
        return view;
    }
    private void initView(){
        watchView = view.findViewById(R.id.watch);
        textView1= view.findViewById(R.id.text1);
        textView2= view.findViewById(R.id.text2);
        textView3= view.findViewById(R.id.text3);
        timeDateWeek=view.findViewById(R.id.time_date_week);
        cityText=view.findViewById(R.id.city);
        cityWhrear=view.findViewById(R.id.city_weather);
        whrearInfo=view.findViewById(R.id.weather_info);
        weatherIcon=view.findViewById(R.id.weather_icon);
        currentTemperature=view.findViewById(R.id.current_temperature);
        hotLayout=view.findViewById(R.id.hot_layout);
        hintText=view.findViewById(R.id.hint_text);
    }

    @SuppressLint("NewApi")
    private void initData(){
        Log.d("Fragment1","private void initData()");
        watchView.start();
        textView1.setOnClickListener(this);
        textView2.setOnClickListener(this);
        textView3.setOnClickListener(this);
//        if (timerTask!=null&&timerTask.cancel()) {

        mLocationClient = new LocationClient(getContext().getApplicationContext());
        //声明LocationClient类
        mLocationClient.registerLocationListener(myListener);
        if(getActivity().checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION)!=PackageManager.PERMISSION_GRANTED&&getActivity().checkSelfPermission(Manifest.permission.READ_PHONE_STATE)!=PackageManager.PERMISSION_GRANTED&&getActivity().checkSelfPermission(Manifest.permission.WRITE_CONTACTS)!=PackageManager.PERMISSION_GRANTED){
            // 申请一个（或多个）权限，并提供用于回调返回的获取码（用户定义）
            requestPermissions( new String[]{Manifest.permission.ACCESS_COARSE_LOCATION,Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.READ_PHONE_STATE,Manifest.permission.WRITE_CONTACTS,Manifest.permission.READ_EXTERNAL_STORAGE,Manifest.permission.WRITE_EXTERNAL_STORAGE, "android.permission.SHUTDOWN"},BAIDU_READ_PHONE_STATE );
        }else {
            Log.d("Fragment1","initbaidu requestPermissions");
            initBaidu();
            App.getINstance().deviceId=PhoneUtil.getDeviceId(getActivity());
        }
//        显示天气
        setTimeAndWeather();

    }

    @RequiresApi(api = Build.VERSION_CODES.O)
    @Override
    public void onRequestPermissionsResult(int requestCode,String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions,grantResults);
        switch(requestCode) {
            //requestCode即所声明的权限获取码，在checkSelfPermission时传入
            case BAIDU_READ_PHONE_STATE:
                if(grantResults[0] == PackageManager.PERMISSION_GRANTED) {

                    initBaidu();
                    Log.d("Fragment1","initbaidu requestPermissions");
                    //获取到权限，做相应处理
                    //调用定位SDK应确保相关权限均被授权，否则会引起定位失败
                }
                if(grantResults[2] == PackageManager.PERMISSION_GRANTED) {

                    //获取到权限，做相应处理
                    //调用定位SDK应确保相关权限均被授权，否则会引起定位失败
                    App.getINstance().deviceId=PhoneUtil.getDeviceId(getActivity());
                }
                break;
            case SECURE_SETTINGS:
//                if(grantResults[0] == PackageManager.PERMISSION_GRANTED) {
//                    openAirplaneModeOn(getActivity(),true);
                    //获取到权限，做相应处理
                    //调用定位SDK应确保相关权限均被授权，否则会引起定位失败
//                } else{
//                    //没有获取到权限，做特殊处理
//                }
            default:
                break;
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.text1:
                Intent intent1=new Intent(getActivity(),IntermediaryActivity.class);
                String pkg1 = "cn.rongcloud.im";
                //应用的主activity类
                String cls1 = "cn.rongcloud.im.ui.activity.SplashActivity";
                intent1.putExtra("pkg",pkg1);
                intent1.putExtra("cls",cls1);
                startActivity(intent1);
                break;
            case R.id.text2:
                Intent intent=new Intent(getActivity(),IntermediaryActivity.class);
                String pkg = "xu.ye";
                //应用的主activity类
                String cls = "xu.ye.view.HomeTabHostAcitivity";
                intent.putExtra("pkg",pkg);
                intent.putExtra("cls",cls);
                startActivity(intent);

                break;
            case R.id.text3:
//                App.getINstance().setsetWaveformMode(2,1);
//                ComponentName componet1 = new ComponentName("com.android.browser", "com.android.browser.BrowserActivity");
//                Intent i1 = new Intent();
//                i1.setComponent(componet1);
//                startActivity(i1);

                Intent intent3=new Intent(getActivity(),IntermediaryActivity.class);

                String pkg3 = "io.github.mthli.Ninja";
                //应用的主activity类
                String cls3 = "io.github.mthli.Ninja.Activity.BrowserActivity";
                intent3.putExtra("pkg",pkg3);
                intent3.putExtra("cls",cls3);
                startActivity(intent3);

                break;
        }
    }


    private Handler mHandle=new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case WHREAR_REQUEST:
                    try {
                        setWeathData(((LauncherActivity1)getActivity()).weatherBean);
                        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("HH:mm MM月 dd 日  EEEE");
                        Calendar calendar = Calendar.getInstance();
                        Date calendarDate = calendar.getTime();
                        String time = simpleDateFormat.format(calendarDate);
                        timeDateWeek.setText(time);
                        if (!TextUtils.isEmpty(city)){
                            cityText.setText(city);
                        }
                    }catch (Exception e){

                    }
//                    if (getActivity()!=null&&!getActivity().isFinishing()) {
//                        ((LauncherActivity1) getActivity()).doProhibit();
//                    }
                    break;
            }


        }
    };
    private void initBaidu(){
        LocationClientOption option = new LocationClientOption();

        option.setLocationMode(LocationClientOption.LocationMode.Hight_Accuracy);
//可选，设置定位模式，默认高精度
//LocationMode.Hight_Accuracy：高精度；
//LocationMode. Battery_Saving：低功耗；
//LocationMode. Device_Sensors：仅使用设备；

        option.setCoorType("bd09ll");
//可选，设置返回经纬度坐标类型，默认GCJ02
//GCJ02：国测局坐标；
//BD09ll：百度经纬度坐标；
//BD09：百度墨卡托坐标；
//海外地区定位，无需设置坐标类型，统一返回WGS84类型坐标

        option.setScanSpan(3*60*1000);
//        option.setScanSpan(1000);
//可选，设置发起定位请求的间隔，int类型，单位ms
//如果设置为0，则代表单次定位，即仅定位一次，默认为0
//如果设置非0，需设置1000ms以上才有效

        option.setOpenGps(true);
//可选，设置是否使用gps，默认false
//使用高精度和仅用设备两种定位模式的，参数必须设置为true

        option.setLocationNotify(true);
//可选，设置是否当GPS有效时按照1S/1次频率输出GPS结果，默认false

        option.setIgnoreKillProcess(false);
//可选，定位SDK内部是一个service，并放到了独立进程。
//设置是否在stop的时候杀死这个进程，默认（建议）不杀死，即setIgnoreKillProcess(true)

        option.SetIgnoreCacheException(false);
//可选，设置是否收集Crash信息，默认收集，即参数为false

        option.setWifiCacheTimeOut(60*60*1000);
//        option.setWifiCacheTimeOut(60*60*1000);
//可选，V7.2版本新增能力
//如果设置了该接口，首次启动定位时，会先判断当前Wi-Fi是否超出有效期，若超出有效期，会先重新扫描Wi-Fi，然后定位

        option.setEnableSimulateGps(false);
        option.setIsNeedAddress(true);
//可选，设置是否需要过滤GPS仿真结果，默认需要，即参数为false

        mLocationClient.setLocOption(option);
//mLocationClient为第二步初始化过的LocationClient对象
//需将配置好的LocationClientOption对象，通过setLocOption方法传递给LocationClient对象使用
//更多LocationClientOption的配置，请参照类参考中LocationClientOption类的详细说明
        mLocationClient.start();
        Log.d("Fragment1","mLocationClient.start(  mLocationClient.start()");
    }

    public class MyLocationListener extends BDAbstractLocationListener {
        @RequiresApi(api = Build.VERSION_CODES.O)
        @Override
        public void onReceiveLocation(BDLocation location){
            //此处的BDLocation为定位结果信息类，通过它的各种get方法可获取定位相关的全部结果
            //以下只列举部分获取经纬度相关（常用）的结果信息
            //更多结果信息获取说明，请参照类参考中BDLocation类中的说明
            int errorCode=location.getLocType();
            Log.d("Fragment1", "onReceiveLocation errorCode=" + errorCode);
            if (errorCode==161||errorCode==61) {

                latitude = location.getLatitude();    //获取纬
                Log.d("", "latitude=" + latitude);
                // 度信息
                longitude = location.getLongitude();    //获取经度信息
                float radius = location.getRadius();    //获取定位精度，默认值为0.0f
                //获取经纬度坐标类型，以LocationClientOption中设置过的坐标类型为准
                city = location.getCity();
                //获取定位类型、定位错误返回码，具体信息可参照类参考中BDLocation类中的说明
//                tianqi jie kou
                Map<String, String> map = new HashMap<String, String>();
                map.put("location", latitude + ":" + longitude);
                if (getActivity()!=null&&((LauncherActivity1)getActivity()).weatherBean==null){
                    NetUtils.post(Url.getweather, map, weatherCallBack);
                    Log.d("Fragment1"," NetUtils.post(Url.getweather, map, weatherCallBack);");
                }else {
                    getWetherFrequency++;
                    if (getWetherFrequency%60==0) {
                        NetUtils.post(Url.getweather, map, weatherCallBack);
                        getWetherFrequency=1;
                        Log.d("Fragment1"," NetUtils.post(Url.getweather, map, weatherCallBack);");
                    }
                }
                Map<String, String> locationMap = new HashMap<String, String>();
                locationMap.put("latitude", latitude + "");
                locationMap.put("longitude", longitude + "");
                if (TextUtils.isEmpty(App.getINstance().deviceId)) {
                    App.getINstance().deviceId = PhoneUtil.getDeviceId(getContext());
                }
                locationMap.put("deviceSerial", App.getINstance().deviceId);

                Log.d("Fragment1", "deviceId=" + App.getINstance().deviceId);
                NetUtils.post(Url.updateLocation, locationMap, locationCallBack);
            }
        }
    }


    private Callback weatherCallBack=new Callback() {
        @Override
        public void onFailure(Call call, IOException e) {
            Log.d("Fragment1","weatherCallBack IOException="+e.getMessage());

        }

        @Override
        public void onResponse(Call call, Response response) throws IOException {
            Log.d("Fragment1","body="+response.body());
            String body=response.body().string();
            Log.d("Fragment1","getWeather body="+body);
            Gson gson = new Gson();
            try {
                WeatherBean weatherBean1=gson.fromJson(body, WeatherBean.class);
                if (null!=weatherBean1) {
                    ((LauncherActivity1)getActivity()).weatherBean = weatherBean1;
                    setTimeAndWeather();
                }

            }catch (Exception e){

            }

        }
    };

    private Callback locationCallBack=new Callback() {
        @Override
        public void onFailure(Call call, IOException e) {
            Log.d("Fragment2","deviceId=="+e.getMessage());

        }

        @Override
        public void onResponse(Call call, Response response) throws IOException {
            Log.d("Fragment2","body="+response.body());
            String body=response.body().string();
            Log.d("Fragment2","locationBody="+body);
        }
    };
    private void setWeathData(WeatherBean weatherBean){
        if (weatherBean==null){
            return;
        }
        String textDay=weatherBean.getDaily().getResults().get(0).getDaily().get(0).getText_day();
        cityWhrear.setText(textDay);
        String low=weatherBean.getDaily().getResults().get(0).getDaily().get(0).getLow()+"℃";
        String  high=weatherBean.getDaily().getResults().get(0).getDaily().get(0).getHigh()+"℃";
        String  current=weatherBean.getNow().getResults().get(0).getNow().getTemperature()+"℃";
        currentTemperature.setText(current);
        whrearInfo.setText(low+"/"+high);
        if (!TextUtils.isEmpty(textDay)){
            if (textDay.contains("暴雨")){
                weatherIcon.setImageResource(R.mipmap.rainstorm);
            }else if (textDay.contains("冰雹")){
                weatherIcon.setImageResource(R.mipmap.hail);
            }else if (textDay.contains("大雪")){
                weatherIcon.setImageResource(R.mipmap.heavy_snow);
            }else if (textDay.contains("大雨")){
                weatherIcon.setImageResource(R.mipmap.heavy_rain);
            }else if ((textDay.contains("多云"))){
                weatherIcon.setImageResource(R.mipmap.cloudy);
            }else if (textDay.contains("雷阵雨")){
                weatherIcon.setImageResource(R.mipmap.thunder_shower);
            }else if (textDay.contains("霾")){
                weatherIcon.setImageResource(R.mipmap.haze);
            }else if (textDay.contains("晴")){
                weatherIcon.setImageResource(R.mipmap.young);
            }else if (textDay.contains("霜冻")){
                weatherIcon.setImageResource(R.mipmap.frost);
            }else if (textDay.contains("台风")){
                weatherIcon.setImageResource(R.mipmap.typhoon);
            }else if (textDay.contains("雾")){
                weatherIcon.setImageResource(R.mipmap.fog);
            }else if (textDay.contains("小雪")){
                weatherIcon.setImageResource(R.mipmap.light_snow);
            }else if (textDay.contains("小雨")){
                weatherIcon.setImageResource(R.mipmap.light_snow);
            }else if (textDay.contains("阴")){
                weatherIcon.setImageResource(R.mipmap.shad);
            }else if (textDay.contains("雨夹雪")){
                weatherIcon.setImageResource(R.mipmap.sleet);
            }else if (textDay.contains("中雪")){
                weatherIcon.setImageResource(R.mipmap.moderate_snow);
            }else if (textDay.contains("中雨")){
                weatherIcon.setImageResource(R.mipmap.moderate_rain);
            }
        }

    }

    public  void openAirplaneModeOn(Context context, boolean enabling) {
        Settings.Global.putInt(context.getContentResolver(),
                Settings.Global.AIRPLANE_MODE_ON,enabling ? 1 : 0);
        Intent intent = new Intent(Intent.ACTION_AIRPLANE_MODE_CHANGED);
        intent.putExtra("state", enabling);
        context.sendBroadcast(intent);
    }


    @Override
    public void onResume() {
        super.onResume();
        App.getINstance().setsetWaveformMode(5,1);
    }

    @Override
    public void onPause() {
        super.onPause();
//        App.getINstance().setsetWaveformMode(2,1);

    }
    public void setTimeAndWeather(){
        Message msg=new Message();
        msg.what=WHREAR_REQUEST;
        mHandle.sendMessage(msg);

    }

    @Override
    public void onStop() {
        super.onStop();

    }
    public void doProhibit(String hintTextValue){
        if (App.getINstance().isProhibit==true){
            if (!TextUtils.isEmpty(hintTextValue)){
               hintText.setText(hintTextValue);
            }
            hintText.setVisibility(View.VISIBLE);
            hotLayout.setVisibility(View.GONE);

        }else {
            hintText.setVisibility(View.GONE);
            hotLayout.setVisibility(View.VISIBLE);
        }
    }






}
